package com.yb.guigu.pick.security.encoder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/3 17:52
 * FileName: GuiguDelegatingPasswordEncoder
 * Description:
 */
@Component
@Primary
@Slf4j
public class GuiguDelegatingPasswordEncoder implements GuiguPasswordEncoder{

    private final List<GuiguPasswordEncoder> encoderList;

    public GuiguDelegatingPasswordEncoder(List<GuiguPasswordEncoder> encoderList){
        log.info("{}",encoderList);
        this.encoderList=encoderList;
    }

    @Override
    public boolean support(String encryptedType) {
        return true;
    }

    @Override
    public String encode(String encryptedType, CharSequence rawPassword) {
        for (GuiguPasswordEncoder guiguPasswordEncoder : encoderList) {
            if(guiguPasswordEncoder.support(encryptedType)){
                return guiguPasswordEncoder.encode(rawPassword);
            }
        }

        throw new BadCredentialsException("不支持的加密类型");
    }

    @Override
    public boolean matches(String encryptedType,CharSequence rawPassword, String encodedPassword) {
        for (GuiguPasswordEncoder guiguPasswordEncoder : encoderList) {
            if(guiguPasswordEncoder.support(encryptedType)){
                return guiguPasswordEncoder.matches(rawPassword,encodedPassword);
            }
        }

        throw new BadCredentialsException("不支持的加密类型");
    }
}
